package com.xmy.cultivate.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.annotaion.RepeatSubmit;
import com.xmy.cultivate.constants.MqConstants;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.entity.views.*;
import com.xmy.cultivate.mapper.StudentMapper;
import com.xmy.cultivate.respons.ResStudentAccount;
import com.xmy.cultivate.respons.SchedulingGrade;
import com.xmy.cultivate.respons.StudentCourse;
import com.xmy.cultivate.service.*;
import com.xmy.cultivate.util.*;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Param;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.xmy.cultivate.util.CommonUtil.validateNumber;

/**
 * <p>
 * 学生表 前端控制器
 * </p>
 *
 * @author min
 * @since 2022-07-19
 */
@RestController
@RequestMapping("/api/student")
public class StudentController extends BaseController {
    @Autowired
    @Lazy
    IStudentService iStudentService;
    @Autowired
    IdWorker idWorker;
    @Autowired
    @Lazy
    IOrderDetailService iOrderDetailService;
    @Autowired
    @Lazy
    ICourseService iCourseService;
    @Autowired
    @Lazy
    IOrderApplyService iOrderApplyService;
    @Autowired
    @Lazy
    ICourseSchedulingDetailService iCourseSchedulingDetailService;
    @Autowired
    @Lazy
    IOssUploadService iOssUploadService;

    @Autowired
    @Lazy
    IQuarterService iQuarterService;

    @Autowired
    @Lazy
    IStudentAccountService iStudentAccountService;

    @Autowired
    @Lazy
    IStudentAtSchoolService iStudentAtSchoolService;

    @Autowired
    @Lazy
    IStudentAtSchoolScoreDivideService iStudentAtSchoolScoreDivideService;

    @Autowired
    @Lazy
    ITranscriptService iTranscriptService;

    @Autowired
    @Lazy
    IStudentSchoolService iStudentSchoolService;

    @Autowired
    @Lazy
    IServiceFeedbackService iServiceFeedbackService;

    @Autowired
    @Lazy
    IStudentGradeService iStudentGradeService;

    @Autowired
    IOrganizationService iOrganizationService;

    @Autowired
    @Lazy
    IGradeService iGradeService;

    @Autowired
    @Lazy
    ITranscriptSetService iTranscriptSetService;

    @Autowired
    @Lazy
    IStaffService iStaffService;

    @Autowired
    @Lazy
    StudentMapper studentMapper;

    @Autowired
    @Lazy
    IRecordCourseService iRecordCourseService;

    @Autowired
    @Lazy
    IStudentSignInService iStudentSignInService;

    @Autowired
    @Lazy
    IStudentMergeLogService iStudentMergeLogService;

    @Autowired
    @Lazy
    IMqPushService iMqPushService;

    @Autowired
    @Lazy
    IAliyunApiService iAliyunApiService;

    @Autowired
    IStudentReadSchoolService iStudentReadSchoolService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Value("${uploadFile.resourceHandler}")
    private String resourceHandler;//请求 url 中的资源映射，不推荐写死在代码中，最好提供可配置，如 /uploadFiles/**
    @Value("${uploadFile.location}")
    private String uploadFileLocation;//上传文件保存的本地目录，使用@Value获取全局配置文件中配置的属性值，如 E:/wmx/uploadFiles/


    @PostMapping("/updateAccount")
    public Result updateAccount(@RequestBody Student student) {
        Result rs = iStudentAccountService.updateAccount(student.getId());
        return rs;
    }

    /**
     * 学员信息
     *
     * @param reMap
     * @return
     */
    @GetMapping()
    public Result findAll(@RequestParam Map reMap, String[] schoolList) {
        Integer pageNum = StringUtils.isEmpty((String) reMap.get("pageNum")) ? 1 : Integer.valueOf((String) reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty((String) reMap.get("pageSize")) ? 10 : Integer.valueOf((String) reMap.get("pageSize"));
        IPage<Student> iPage = new Page<>(pageNum, pageSize);
        //String status = (String) reMap.get("status");
        String name = (String) reMap.get("name");
        String status = (String) reMap.get("status");
        QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(name)) {
            studentQueryWrapper.and(i -> i.like("name", name).or(j -> j.like("linkman_phone", name)));
        }
        Long schoolId = 0L;
        if (schoolList.length > 0) {
            String ss = String.join(",", schoolList);
            studentQueryWrapper.inSql("id", "select student_id from order_apply where school_id in(" + ss + ") and deleted=0 and status<>2 group by student_id");
            schoolId = Long.parseLong(schoolList[0]);
        } else {
            studentQueryWrapper.inSql("id", "select student_id from order_apply where school_id in(" + baseSchoolIdStr + ") and deleted=0 and status<>2 group by student_id");
        }
        studentQueryWrapper.eq("deleted", 0);
        iStudentService.findAll(iPage, studentQueryWrapper, schoolId);
        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));
    }

    /**
     * 人脸采集获取学员信息
     *
     * @param reMap
     * @return
     */
    @GetMapping("/signCheckStuList")
    public Result signStuList(@RequestParam Map reMap, String[] schoolList) {
        Integer pageNum = StringUtils.isEmpty((String) reMap.get("pageNum")) ? 1 : Integer.valueOf((String) reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty((String) reMap.get("pageSize")) ? 10 : Integer.valueOf((String) reMap.get("pageSize"));
        IPage<Student> iPage = new Page<>(pageNum, pageSize);
        String name = (String) reMap.get("name");
        String status = (String) reMap.get("status");
        QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(name)) {
            studentQueryWrapper.and(i -> i.like("name", name).or(j -> j.like("linkman_phone", name)));
        }
        Long schoolId = 0L;
        if (schoolList.length > 0) {
            String ss = String.join(",", schoolList);
            studentQueryWrapper.and(i -> i.inSql("id", "select student_id from order_apply where school_id in(" + ss + ") and deleted=0 and status<>2 group by student_id").or().eq("stu_type", 2).inSql("id", "select student_id from student_school where school_id in(" + ss + ")"));
            //studentQueryWrapper.inSql("id", "select student_id from order_apply where school_id in(" + ss + ") and deleted=0 and status<>2 group by student_id");
            schoolId = Long.parseLong(schoolList[0]);
        } else {
            studentQueryWrapper.in("school_id", 0);
        }
        studentQueryWrapper.eq("deleted", 0);
        iStudentService.findAll(iPage, studentQueryWrapper, schoolId);
        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));
    }

    /**
     * 花名册
     *
     * @param reMap
     * @param schoolList
     * @return
     */
    @GetMapping("/rosterList")
    public Result rosterList(@RequestParam Map<String, String> reMap, @RequestParam(value = "isScheduling", defaultValue = "") String isScheduling, @RequestParam("schoolList") String[] schoolList) {
        Integer pageNum = StringUtils.isEmpty(reMap.get("pageNum")) ? 1 : Integer.valueOf(reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty(reMap.get("pageSize")) ? 10 : Integer.valueOf(reMap.get("pageSize"));
        IPage<Student> iPage = new Page<>(pageNum, pageSize);
        String keywordType = reMap.get("keywordSearchType");
        String keyword = reMap.get("name");
        String state = reMap.get("state");
        String isGuanzhu = reMap.get("isGuanzhu");
        String isGather = reMap.get("isGather");
        String isOwn = reMap.get("isOwn");
        String isCourseHouse = reMap.get("isCourseHouse");
        String isIdCard = reMap.get("isIdCard");
        String isNew = reMap.get("isNew");
        String subjectsId = reMap.get("subjectsId");

        Quarter quarterNow = iQuarterService.getNowQuarter();

        Long schoolId = 0L;
        String schoolIdStr = "";
        if (schoolList.length > 0) {
            schoolIdStr = String.join(",", schoolList);
            schoolId = Long.parseLong(schoolList[0]);
        } else {
            schoolIdStr = baseSchoolIdStr;
        }

        iStudentService.rosterList(iPage, quarterNow.getYearPart(), quarterNow.getNum(), schoolId, schoolIdStr, state, isGuanzhu, isGather, isOwn, isIdCard, isCourseHouse, isScheduling, keywordType, keyword, this.sourseLeve, this.adminId);

        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));
    }

    /**
     * 花名删获取欠费
     *
     * @param reMap
     * @param schoolList
     * @return
     */
    @GetMapping("/arrearage")
    public Result arrearage(@RequestParam Map<String, String> reMap, String[] schoolList) {

        //String status = (String) reMap.get("status");
        /*String keywordSearchType = (String)reMap.get("keywordSearchType");
        String name = (String)reMap.get("name");
        String state = (String)reMap.get("state");
        String isGuanzhu = (String)reMap.get("isGuanzhu");
        String isGather = (String)reMap.get("isGather");
        String isOwn = (String)reMap.get("isOwn");
        String isNew = (String)reMap.get("isNew");

        QueryWrapper<Student> studentQueryWrapper =  new QueryWrapper<>();

        if(StringUtils.isNotBlank(name)){
            if(keywordSearchType!=null && keywordSearchType.equals("1")){
                studentQueryWrapper.like("name",name);
            }else {
                studentQueryWrapper.like("linkman_phone",name);
            }
            //studentQueryWrapper.and(i->i.like("name",name).or(j->j.like("linkman_phone",name)));
        }
        //studentQueryWrapper.eq(StringUtils.isNotBlank(state),"state",state);
        studentQueryWrapper.eq(StringUtils.isNotBlank(isGuanzhu),"is_guanzhu",isGuanzhu);
        studentQueryWrapper.eq(StringUtils.isNotBlank(isGather),"is_gather",isGather);

        if(StringUtils.isNotBlank(isOwn)){
            if(isOwn.equals("1")){
                studentQueryWrapper.inSql("id","select student_id from order_apply where own_price>0 and status<>2 and is_own = 1");
            }else{
                studentQueryWrapper.inSql("id","select student_id from order_apply where own_price = 0 and status<>2 and is_own = 0");
            }
        }

        if(StringUtils.isNotBlank(isNew)){

        }
        if(schoolList.length > 0){
            studentQueryWrapper.in("school_id",schoolList);
        }else{
            studentQueryWrapper.in("school_id",this.baseSchoolIdList);
        }

        BigDecimal arrearageMoney =  iStudentService.arrearage(studentQueryWrapper);*/

        return new Result(Code.OK, 0);
    }


    /**
     * 报名获取学员信息
     *
     * @param reMap
     * @return
     */
    @GetMapping("signUpStu")
    public Result signUpStu(@RequestParam Map reMap,
                            @RequestParam(value = "excludeStudentId",required = false) Long excludeStudentId) {
        /*Date startDateTime = DateUtil.StrToDateTime("2022-08-03" +" "+ "03:20:00");
            Date endDateTime = DateUtil.StrToDateTime("2022-08-03" +" "+ "10:20:00");
            System.out.print(startDateTime +"---endDateTime:"+ endDateTime);*/

        //StringUtils.isEmpty(reMap.get("pageNum"));
        Integer pageNum = StringUtils.isEmpty((String) reMap.get("pageNum")) ? 1 : Integer.valueOf((String) reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty((String) reMap.get("pageSize")) ? 10 : Integer.valueOf((String) reMap.get("pageSize"));
        IPage<Student> iPage = new Page<>(pageNum, pageSize);
        //String status = (String) reMap.get("status");
        String keyword = (String) reMap.get("keyword");

        //订单类型：1报名，2补费，3转课，4退费
        String type = (String) reMap.get("type");
        QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
        studentQueryWrapper.eq("status", 1);
        studentQueryWrapper.orderByDesc("created_at");
        studentQueryWrapper.eq("deleted", 0);

        if (type.equals("2")) {
            studentQueryWrapper.inSql("id", "select student_id from order_apply where is_own = 1 and status <> 2");
        } else if (type.equals("3")) {
            studentQueryWrapper.inSql("id", "select student_id from order_detail where residue_course_count > 0 and status <> 2");
        } else if (type.equals("4")) {
            studentQueryWrapper.inSql("id", "select student_id from order_detail where residue_course_count > 0 and status <> 2");
        }

        if (StringUtils.isNotBlank(keyword)) {
            studentQueryWrapper.and(i -> i.like("name", keyword).or(j -> j.like("linkman_phone", keyword)));
        }

        //studentQueryWrapper.in("school_id",this.baseSchoolIdList);
        studentQueryWrapper.inSql("id", "select id from staff where school_id in(" + baseSchoolIdStr + ")");
        //studentQueryWrapper.inSql("id","select student_id from order_apply where school_id in("+baseSchoolIdStr+") and deleted=0 and status<>2 group by student_id");

        if(excludeStudentId!=null){
            studentQueryWrapper.ne("id", excludeStudentId);
        }


        iStudentService.findAll(iPage, studentQueryWrapper, 0L);

        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));
    }

    /**
     * 获取一条学员数据
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result findById(@PathVariable(value = "id") Long id) {
        Student student = iStudentService.findOne(id);
        student.setGradeId(student.getYearClassId());
        //long ids =  idWorker.nextId();
        //System.out.println(ids);

//        Integer gradeSectionId = CommonUtil.getGradeSectionId(Integer.valueOf(student.getYearClassId()));
//        QueryWrapper wrapper = new QueryWrapper<>();
//        wrapper.eq("grade_section", gradeSectionId);
//        wrapper.eq("student_id", student.getId());
//        wrapper.last("LIMIT 1");
//        StudentReadSchool studentReadSchool = iStudentReadSchoolService.getOne(wrapper);

        return new Result(Code.OK, student);
    }


    @PostMapping()
    @RepeatSubmit(expireSeconds = 5)
    public Result save(@RequestBody Student student) {
        List<TypeValueData> typeValueDataList = student.getLinkManList();
        if (typeValueDataList.size() > 0) {
            String phone = typeValueDataList.get(0).getContent();
            student.setLinkmanPhone(phone);
        } else {
            return new Result(Code.ERROR, "", "手机号不能为空");
        }
        if (student.getStuType() != null && student.getStuType().equals(2)) {
            boolean rsVerify = iAliyunApiService.verifyCode(student.getLinkmanPhone(), student.getVerifyCode(), this.adminId);
            if (!rsVerify) {
                return new Result(Code.ERROR, "", "验证码不正确");
            }
        } else {
            Integer tryCount = iStudentService.getTryStudentForNameCount(student.getName(), student.getSchoolId());
            if (tryCount > 0) {
                return new Result(Code.ERROR, "", "存在同名的试听学生，请输入学生姓名报名");
            }
        }

        //dict.setId(idWorker.nextId());
        if (student.getSchoolId() == null) {
            if (baseSchoolIdList.size() > 0) {
                student.setSchoolId(baseSchoolIdList.get(0));
            }
        }

        if (StringUtils.isNotBlank(student.getIdCardNo())) {
            QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
            studentQueryWrapper.eq("id_card_no", student.getIdCardNo().trim());
            //studentQueryWrapper.eq("school_id",student.getSchoolId());
            studentQueryWrapper.last("limit 1");
            Student studentInfo = iStudentService.getOne(studentQueryWrapper);
            if (studentInfo != null) {
                iStudentSchoolService.addOrUpdateData(studentInfo.getId(), student.getSchoolId());
                if (student.getName().trim().equals(studentInfo.getName().trim())) {
                    return new Result(Code.OK, "", "此身份证已添加过同名学生，该学员已更新到该校区，请重新搜索报名");
                } else {
                    return new Result(Code.ERROR, "", "添加失败，此身份证下存在姓名：" + studentInfo.getName() + "，请确认是否为同一个学生，并使用之报名");
                }
                //return new Result(Code.ERROR,"","此身份证号已存在学生，姓名为："+studentInfo.getName()+",不要重复添加");
            }
        } else if (StringUtils.isNotBlank(student.getLinkmanPhone())) {
            QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
            studentQueryWrapper.eq("name", student.getName().trim());
            studentQueryWrapper.eq("linkman_phone", student.getLinkmanPhone().trim());
            //studentQueryWrapper.eq("school_id",student.getSchoolId());
            studentQueryWrapper.last("limit 1");
            Student studentInfo = iStudentService.getOne(studentQueryWrapper);
            if (studentInfo != null) {
                iStudentSchoolService.addOrUpdateData(studentInfo.getId(), student.getSchoolId());
                if (student.getName().trim().equals(studentInfo.getName().trim())) {
                    return new Result(Code.OK, "", "此身份证已添加过同名学生，该学员已更新到该校区，请重新搜索报名");
                } else {
                    return new Result(Code.ERROR, "", "添加失败，此手机号下存在姓名：" + studentInfo.getName() + "，请确认是否为同一个学生，并使用之报名");
                }
                //return new Result(Code.ERROR,"","此身份证号已存在学生，姓名为："+studentInfo.getName()+",不要重复添加");
            }
        }


        String verifyScore = iTranscriptService.verifyScore(student);
        if (!verifyScore.equals("true")) {
            return new Result(Code.ERROR, "", verifyScore);
        }

        student.setName(student.getName().trim());
        StudentAtSchool studentAtSchool = iStudentAtSchoolService.getById(student.getReadingSchoolId());
        /*if (studentAtSchool == null){
            return new Result(Code.ERROR,"","在读学校不存在，请联系校长添加");
        }else {
            QueryWrapper<StudentAtSchoolScoreDivide> studentAtSchoolScoreDivideQueryWrapper = new QueryWrapper<>();
            studentAtSchoolScoreDivideQueryWrapper.eq("student_at_school_id",student.getReadSchoolId());
            studentAtSchoolScoreDivideQueryWrapper.eq("grade_section",studentAtSchool.getGradeSection());
            studentAtSchoolScoreDivideQueryWrapper.eq("score",student.getScore().trim());
            studentAtSchoolScoreDivideQueryWrapper.last("limit 1");
            StudentAtSchoolScoreDivide studentAtSchoolScoreDivide = iStudentAtSchoolScoreDivideService.getOne(studentAtSchoolScoreDivideQueryWrapper);
            if (studentAtSchoolScoreDivide == null){
                return new Result(Code.ERROR,"","分段不存在，请联系校长添加");
            }
        }*/

        boolean rs = iStudentService.saveTo(student);

        // 添加到学生校区表（公立）中
        if (student.getReadingSchoolId() != null) {
            Quarter quarter = iQuarterService.getNowQuarter();
            Integer gradeSectionId = CommonUtil.getGradeSectionId(student.getYearClassId());
            StudentReadSchool studentReadSchool = new StudentReadSchool();
            studentReadSchool.setStudentId(student.getId());
            studentReadSchool.setYearPart(quarter.getYearPart());
            studentReadSchool.setQuarterNum(quarter.getNum());
            studentReadSchool.setYearClassId(student.getYearClassId());
            studentReadSchool.setGradeSection(gradeSectionId);
            studentReadSchool.setReadingSchoolId(student.getReadingSchoolId());
            iStudentReadSchoolService.save(studentReadSchool);
        }

        return new Result(rs ? Code.OK : Code.ERROR);
    }

    @PostMapping("/addTrascript")
    public Result addTrascript(@RequestBody Student student) {
        iTranscriptService.addTrascript(student);
        return new Result(Code.OK, student);
    }


    /**
     * 修改身份证
     *
     * @param studentParam
     * @return
     */
    @PostMapping("/updateIdCard")
    public Result updateIdCard(@RequestBody Student studentParam) {
        Student student = iStudentService.getById(studentParam.getId());
        if (student == null) {
            return new Result(Code.ERROR, "", "学生不存在");
        }

        QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
        studentQueryWrapper.eq("id_card_no", studentParam.getIdCardNo().trim());
        studentQueryWrapper.ne("id", student.getId());
        studentQueryWrapper.last("limit 1");
        Student studentInfo = iStudentService.getOne(studentQueryWrapper);
        Map<String, Object> map = new HashMap<>();
        if (studentInfo != null) {
            if (student.getName().trim().equals(studentInfo.getName().trim())) {
                QueryWrapper<OrderApply> orderApplyQueryWrapper = new QueryWrapper<>();
                orderApplyQueryWrapper.eq("student_id", student.getId());
                orderApplyQueryWrapper.ne("status", 2);
                Long count = iOrderApplyService.count(orderApplyQueryWrapper);
                if (count > 0) {
                    return new Result(Code.ERROR, "", "已经报名，不能在这里修改");
                }

                iStudentSchoolService.addOrUpdateData(studentInfo.getId(), student.getSchoolId());
                UpdateWrapper<RecordCourse> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("student_id", student.getId());
                //updateWrapper.eq("check_type", 1);
                updateWrapper.set("student_id", studentInfo.getId());
                iRecordCourseService.update(updateWrapper);

                UpdateWrapper<StudentSignIn> signInUpdateWrapper = new UpdateWrapper<>();
                signInUpdateWrapper.eq("student_id", student.getId());
                signInUpdateWrapper.set("student_id", studentInfo.getId());
                iStudentSignInService.update(signInUpdateWrapper);

                StudentMergeLog studentMergeLog = new StudentMergeLog();
                studentMergeLog.setStudentId(student.getId());
                studentMergeLog.setToStudentId(studentInfo.getId());
                studentMergeLog.setRemark("身份证证时合并");
                iStudentMergeLogService.save(studentMergeLog);

                iMqPushService.delStudentFaceData(student.getId());
                studentMapper.deleteById(student.getId());
                map.put("isUpdate", 1);
                map.put("student", studentInfo);
                return new Result(Code.OK, map, "身份证录入成功");
            } else {
                return new Result(Code.ERROR, "", "身份证录入失败，此身份证下存在姓名：" + studentInfo.getName() + "，请确认是否为同一个学生，如果是请把姓名修改一致");
            }
            //return new Result(Code.ERROR,"","此身份证号已存在学生，姓名为："+studentInfo.getName()+",不要重复添加");
        }

        student.setIdCardNo(studentParam.getIdCardNo().trim());
        iStudentService.updateById(student);
        map.put("isUpdate", 0);
        map.put("student", student);
        return new Result(Code.OK, map, "身份证录入成功");
    }


    @PutMapping("/{id}")
    public Result update(@PathVariable(value = "id") String id, @RequestBody Student student) {
        if (student.getId() == null) {
            return new Result(Code.ERROR, "", "id不能为空");
        }

        Student studentOld = iStudentService.getById(student.getId());

        if (student.getLinkManList().size() == 1) {
            String phone = "";
            for (TypeValueData typeValueData : student.getLinkManList()) {
                phone = typeValueData.getContent().trim();
            }
            //修改时，只有一个手机号码，并且和原来的号码一样，不做验证与修改
            if (!phone.equals(studentOld.getLinkmanPhone())) {
                // 修改手机号
                iStudentService.updatePhoneNumNew(id, student);
            }
        } else {
            // 修改手机号
            iStudentService.updatePhoneNumNew(id, student);
        }

        String verifyScore = iTranscriptService.verifyScore(student);
        if (!verifyScore.equals("true")) {
            return new Result(Code.ERROR, "", verifyScore);
        }
        //System.out.println(dict);
        if (StringUtils.isNotBlank(student.getIdCardNo())) {
            QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
            studentQueryWrapper.eq("id_card_no", student.getIdCardNo());
            studentQueryWrapper.eq("school_id", student.getSchoolId());
            studentQueryWrapper.ne("id", student.getId());
            studentQueryWrapper.notInSql("id", "select id from student where deleted=0 and name like '%" + student.getName().trim() + "%'");
            studentQueryWrapper.last("limit 1");
            Student studentInfo = iStudentService.getOne(studentQueryWrapper);
            if (studentInfo != null) {
                return new Result(Code.ERROR, "", "此身份证号已存在学生，姓名为：" + studentInfo.getName() + ",不要重复添加");
            }
        }
        student.setName(student.getName().trim());

        boolean rs = iStudentService.updateTo(student);
        iStudentAccountService.updateAccount(student.getId());

        // 添加到学生校区表（公立）中
        if (student.getReadingSchoolId() != null) {
            Quarter quarter = iQuarterService.getNowQuarter();
            Integer gradeSectionId = CommonUtil.getGradeSectionId(student.getYearClassId());

            QueryWrapper wrapper = new QueryWrapper<>();
            wrapper.eq("grade_section", gradeSectionId);
            wrapper.eq("student_id", student.getId());
            wrapper.last("LIMIT 1");
            StudentReadSchool studentReadSchool = iStudentReadSchoolService.getOne(wrapper);
            if (studentReadSchool == null) {
                studentReadSchool = new StudentReadSchool();
                studentReadSchool.setStudentId(student.getId());
                studentReadSchool.setYearPart(quarter.getYearPart());
                studentReadSchool.setQuarterNum(quarter.getNum());
                studentReadSchool.setYearClassId(student.getYearClassId());
                studentReadSchool.setGradeSection(gradeSectionId);
                studentReadSchool.setReadingSchoolId(student.getReadingSchoolId());
                iStudentReadSchoolService.save(studentReadSchool);
            } else {
                studentReadSchool.setYearPart(quarter.getYearPart());
                studentReadSchool.setQuarterNum(quarter.getNum());
                studentReadSchool.setYearClassId(student.getYearClassId());
                studentReadSchool.setReadingSchoolId(student.getReadingSchoolId());
                iStudentReadSchoolService.updateById(studentReadSchool);
            }
        }

        ResStudentAccount resStudentAccount = new ResStudentAccount();
        resStudentAccount.setLinkmanPhone(student.getLinkmanPhone());
        resStudentAccount.setStudentId(student.getId());
        resStudentAccount.setLinkman(student.getLinkman());

        //rabbitTemplate.convertAndSend(MqConstants.EXCHANGE_SYNC_EXCLUDE_PHONE_FANOUT,null,resStudentAccount);
        return new Result(rs ? Code.OK : Code.ERROR);
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable(value = "id") Long id) {

        QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
        orderDetailQueryWrapper.eq("deleted", 0);
        orderDetailQueryWrapper.ne("status", 2);
        orderDetailQueryWrapper.eq("student_id", id);
        Long count = iOrderDetailService.count(orderDetailQueryWrapper);
        if (count > 0) {
            return new Result(Code.ERROR, "存在报名数据，不能删除");
        }

        boolean rs = iStudentService.removeById(id);
        return new Result(rs ? Code.OK : Code.ERROR);
    }

    /**
     * 花名册——新增联系人
     */
    @PutMapping("phoneNum/{id}")
    public Result updatePhoneNum(@PathVariable(value = "id") String id, @RequestBody Student student) {
        if (StringUtils.isBlank(id)) {
            return new Result(Code.ERROR, "", "id不能为空");
        }

        String rs = iStudentService.updatePhoneNum(id, student);

        ResStudentAccount resStudentAccount = new ResStudentAccount();
        resStudentAccount.setLinkmanPhone(student.getLinkmanPhone());
        resStudentAccount.setStudentId(student.getId());
        resStudentAccount.setLinkman(student.getLinkman());
        //rabbitTemplate.convertAndSend(MqConstants.EXCHANGE_SYNC_EXCLUDE_PHONE_FANOUT,null,resStudentAccount);

        if (rs.equals("成功")) {
            return new Result(Code.OK, "", Code.OK_MSG);
        } else {
            return new Result(Code.ERROR, "手机号填写有误", rs);
        }
    }

    /**
     * 分班列表
     *
     * @param reMap
     * @return
     */
    @GetMapping("divideList")
    public Result divideList(@RequestParam Map reMap) {
        //boolean rs =  iStudentService.removeById(id);
        return new Result(Code.OK);
    }

    /**
     * 报读列表
     *
     * @return
     */
    @GetMapping("/enrollList")
    public Result enrollList(@RequestParam Map reMap,
                             @RequestParam(value = "schoolIdList", defaultValue = "") String[] schoolIdList,
                             @RequestParam(value = "yearClassIdList", defaultValue = "") String[] yearClassIdList,
                             @RequestParam(value = "readingStatusList", defaultValue = "") String[] readingStatusList,
                             @RequestParam(value = "courseIdList", defaultValue = "") String[] courseIdList) {
        Integer pageNum = StringUtils.isEmpty((String) reMap.get("pageNum")) ? 1 : Integer.valueOf((String) reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty((String) reMap.get("pageSize")) ? 10 : Integer.valueOf((String) reMap.get("pageSize"));


        String keyType = (String) reMap.get("keyType");
        String keyWord = (String) reMap.get("keyWord");
        String subjectsId = (String) reMap.get("subjectsId");


        //System.out.print(schoolIds.length);


        IPage<EnrollList> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Map<String, Object>> queryWrapper = new QueryWrapper<>();

        //queryWrapper.in(schoolIds.length>0,"schoolId",schoolIds);

        if (schoolIdList.length > 0) {
            queryWrapper.in("school_id", schoolIdList);
        } else {
            queryWrapper.in("school_id", this.baseSchoolIdList);
        }
        if (yearClassIdList.length > 0) {
            queryWrapper.in("year_class_id", yearClassIdList);
        }

        if (readingStatusList.length > 0) {
            queryWrapper.in("reading_status", readingStatusList);
        }

        if (courseIdList.length > 0) {
            queryWrapper.in("course_id", courseIdList);
        }

        if (StringUtils.isNotBlank(keyWord)) {
            if (keyType.equals("1")) {
                queryWrapper.like("student_name", keyWord);
            }
        }

        if (StringUtils.isNotBlank(subjectsId)) {
            queryWrapper.eq("subjects_id", subjectsId);
        }

        queryWrapper.eq("deleted", 0);
        queryWrapper.ne("status", 2);
        if (this.sourseLeve.equals(2)) {
            queryWrapper.inSql("student_id", "select student_id from student_grade_view where deleted = 0 and teacher_id =" + this.adminId);
        }


        iOrderDetailService.getEnrollList(page, queryWrapper);
        return new Result(Code.OK, new PageResult(page.getRecords(), page.getTotal(), page.getPages()));
    }

    @GetMapping("/enrollListMoney")
    public Result enrollListMoney(@RequestParam Map reMap,
                                  @RequestParam(value = "schoolIdList", defaultValue = "") String[] schoolIdList,
                                  @RequestParam(value = "yearClassIdList", defaultValue = "") String[] yearClassIdList,
                                  @RequestParam(value = "readingStatusList", defaultValue = "") String[] readingStatusList,
                                  @RequestParam(value = "courseIdList", defaultValue = "") String[] courseIdList) {
        String keyType = (String) reMap.get("keyType");
        String keyWord = (String) reMap.get("keyWord");
        String subjectsId = (String) reMap.get("subjectsId");

        QueryWrapper<Map<String, Object>> queryWrapper = new QueryWrapper<>();

        //queryWrapper.in(schoolIds.length>0,"schoolId",schoolIds);

        if (schoolIdList.length > 0) {
            queryWrapper.in("school_id", schoolIdList);
        } else {
            queryWrapper.in("school_id", this.baseSchoolIdList);
        }
        if (yearClassIdList.length > 0) {
            queryWrapper.in("year_class_id", yearClassIdList);
        }

        if (readingStatusList.length > 0) {
            queryWrapper.in("reading_status", readingStatusList);
        }

        if (courseIdList.length > 0) {
            queryWrapper.in("course_id", courseIdList);
        }

        if (StringUtils.isNotBlank(keyWord)) {
            if (keyType.equals("1")) {
                queryWrapper.like("student_name", keyWord);
            }
        }

        if (StringUtils.isNotBlank(subjectsId)) {
            queryWrapper.eq("subjects_id", subjectsId);
        }

        queryWrapper.eq("deleted", 0);
        queryWrapper.ne("status", 2);

        Map<String, BigDecimal> map = iOrderDetailService.enrollListMoney(queryWrapper);

        return new Result(Code.OK, map);
    }


    @GetMapping("/orderForStuId/{studentId}/{pageNum}/{pageSize}")
    public Result orderForStuId(@PathVariable(value = "studentId") Long studentId,
                                @PathVariable(value = "pageNum") Integer pageNum,
                                @PathVariable(value = "pageSize") Integer pageSize) {
        IPage<OrderApply> iPage = new Page<>(pageNum, pageSize);
        //获取一个学员的订单信息用到
        if (studentId == null) {
            studentId = 0L;
        }
        QueryWrapper<OrderApply> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("studentId", studentId);
        queryWrapper.orderByDesc("created_at");
        queryWrapper.eq("deleted", 0);
        queryWrapper.ne("status", 2);

        queryWrapper.in("school_id", this.baseSchoolIdList);

        iOrderApplyService.findAll(iPage, queryWrapper);

        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));
    }

    @GetMapping("/studentCourse/{studentId}/{pageNum}/{pageSize}")
    public Result studentCourse(@RequestParam(value = "subjectsId", defaultValue = "") String subjectsId,
                                @PathVariable(value = "studentId") Long studentId,
                                @RequestParam(value = "lessonType", defaultValue = "1", required = false) String lessonType,
                                @PathVariable(value = "pageNum") Integer pageNum,
                                @PathVariable(value = "pageSize") Integer pageSize) {
        IPage<Map<String, Object>> iPage = new Page<>(pageNum, pageSize);
        QueryWrapper<Course> courseQueryWrapper = new QueryWrapper<>();

        courseQueryWrapper.eq("student_id", studentId);
        courseQueryWrapper.orderByDesc("id");
        courseQueryWrapper.eq("deleted", 0);
        courseQueryWrapper.ne("status", 2);
        courseQueryWrapper.eq(StringUtils.isNotBlank(subjectsId), "subjects_id", subjectsId);

        courseQueryWrapper.in("school_id", this.baseSchoolIdList);


        iCourseService.studentCourse(iPage, courseQueryWrapper, Integer.parseInt(lessonType));
        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));
    }

    /**
     * 我的课程表
     *
     * @param reMap
     * @param studentId
     * @return
     */
    @GetMapping("myScheduling/{studentId}")
    public Result myScheduling(@RequestParam Map reMap, @RequestParam(value = "studentId") Long studentId) {
        QueryWrapper<CourseSchedulingDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0);

        queryWrapper.inSql("grade_id", "select grade_id from student_grade as b where course_id in (select course_id from order_detail as a where a.student_id = " + studentId + " and deleted=0 and status<>2 and reading_status=1) and reading_status = 1 ");

        //courseSchedulingDetailQueryWrapper.orderByDesc("")
        List<CourseSchedulingDetail> courseSchedulingDetailList = iCourseSchedulingDetailService.findAll(queryWrapper);

        return new Result(Code.OK, new PageResult(courseSchedulingDetailList, (long) courseSchedulingDetailList.size(), 1L));
    }

    @GetMapping("isAt")
    public Result isAt(@RequestParam Map reMap) {

        String name = (String) reMap.get("name");
        String remark = (String) reMap.get("remark");

        QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(name)) {
            studentQueryWrapper.eq("name", name);
        }

        if (StringUtils.isNotBlank(remark)) {
            studentQueryWrapper.eq("remark", remark);
        }

        Long schoolId = null;

        if (this.isSuper.equals(1)) {

        } else {
            studentQueryWrapper.in("school_id", this.baseSchoolIdList);
        }


        Long count = iStudentService.count(studentQueryWrapper);
        return new Result(Code.OK, count);
    }


    @ApiOperation("学生个人出勤统计-新功能 2023.11.4")
    @GetMapping("attendance")
    public Result attendance(@RequestParam Map reMap) {
        String yearPart = null;//选传
        if (reMap.get("yearPart") != null && !Objects.equals(reMap.get("yearPart").toString(), "")) {
            yearPart = reMap.get("yearPart").toString();
        }
        String quarterNum = null;//选传
        if (reMap.get("quarterNum") != null && !Objects.equals(reMap.get("quarterNum").toString(), "")) {
            quarterNum = reMap.get("quarterNum").toString();
        }
        String studentId = null;//必传，不传会报错
        if (reMap.get("studentId") != null && !Objects.equals(reMap.get("studentId").toString(), "")) {
            studentId = reMap.get("studentId").toString();
        }
        String subjectsId = "1";//科目 1 英语；2 数学；3 物理。默认 1 英语
        if (reMap.get("subjectsId") != null && !Objects.equals(reMap.get("subjectsId").toString(), "")) {
            subjectsId = reMap.get("subjectsId").toString();
        }
        List<ServiceFeedback> feedBadckAttendanceList = iServiceFeedbackService.getFeedBadckAttendanceList(studentId, yearPart, quarterNum, subjectsId);
        ArrayList<Object> arrayList = new ArrayList<>();
        if (feedBadckAttendanceList.size() < 15) {
            for (int i = 1; i <= 15; i++) {
                ServiceFeedback serviceFeedback = new ServiceFeedback();
                if (!feedBadckAttendanceList.isEmpty()) {
                    for (ServiceFeedback serviceFeedback1 : feedBadckAttendanceList) {
                        if (serviceFeedback1.getLessonNum() == i) {
                            serviceFeedback = serviceFeedback1;
                        }
                    }
                }
                serviceFeedback.setLessonNum(i);
                arrayList.add(serviceFeedback);
            }
        }
        if (arrayList.isEmpty()) {
            arrayList.addAll(feedBadckAttendanceList);
        }
        return new Result(Code.OK, arrayList);
    }

    /**
     * 批量更新智能课班型与教师
     *
     * @return
     */
    @GetMapping("/batchUpdateStudentAccount")
    public Result batchUpdateStudentAccount(@RequestParam(value = "yearPart", required = true) Integer yearPart,
                                            @RequestParam(value = "quarterNum", required = true) Integer quarterNum,
                                            @RequestParam(value = "subjectsId", required = false, defaultValue = "1") Long subjectsId,
                                            @RequestParam(value = "lessonType", required = false, defaultValue = "1") Integer lessonType
    ) {
        iStudentGradeService.batchUpdateStudentAccount(yearPart, quarterNum, subjectsId, lessonType);
        return new Result(Code.OK, "", "更新中……");
    }

    /**
     * 排班人数
     *
     * @param reMap
     * @return
     */
    @GetMapping("/studentCount")
    @ApiOperation("排班人数")
    public Result studentCount(@RequestParam Map reMap) {
        String schoolIds = (String) reMap.get("schoolIds");
        String yearPart = (String) reMap.get("yearPart");
        String quarterNum = (String) reMap.get("quarterNum");
        String subjectsId = (String) reMap.get("subjectsId");
        String classTypeId = (String) reMap.get("classTypeId");
        String status = (String) reMap.get("status");
        String startDate = (String) reMap.get("startDate");
        String endDate = (String) reMap.get("endDate");

        List<Student> studentList = iStudentService.getStudentCount(schoolIds, subjectsId, yearPart, quarterNum, classTypeId, Integer.valueOf(status), startDate, endDate);

        List<Map<String, Object>> mapList = new ArrayList<>();
        Map<Long, Map<String, Object>> schoolGradeCountMap = new HashMap<>();

        for (Student student : studentList) {
            Long schoolId = student.getSchoolId();
            Integer yearClassId = student.getYearClassId();
            int studentCount = student.getCount();
            if (!schoolGradeCountMap.containsKey(schoolId)) {
                schoolGradeCountMap.put(schoolId, new HashMap<>());
            }
            Map<String, Object> gradeCountMap = schoolGradeCountMap.get(schoolId);
            String englishYearClassId = convertToEnglish(yearClassId);
            gradeCountMap.put(englishYearClassId, (Integer)gradeCountMap.getOrDefault(englishYearClassId, 0) + studentCount);
            String countKey = "count";
            gradeCountMap.put(countKey, (Integer)gradeCountMap.getOrDefault(countKey, 0) + studentCount);
        }

        Integer total = 0;
        for (Map.Entry<Long, Map<String, Object>> entry : schoolGradeCountMap.entrySet()) {
            Long schoolId = entry.getKey();
            Map<String, Object> gradeCountMap = entry.getValue();
            Map<String, Object> schoolMap = new LinkedHashMap<>();
            schoolMap.put("schoolId", schoolId);
            schoolMap.put("schoolName", iOrganizationService.getSchoolName(schoolId));
            //schoolMap.put("count", iStudentService.getStudentCountBySchoolId(String.valueOf(schoolId), subjectsId, yearPart, quarterNum, classTypeId, Integer.valueOf(status), startDate, endDate));
            schoolMap.putAll(gradeCountMap);
            mapList.add(schoolMap);
            total++;
        }

        //返回内容
        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("content", mapList);
        hashMap.put("total", total);

        return new Result(Code.GET_OK, hashMap, Code.GET_OK_MSG);
    }

    /**
     * 数字转换为对应的英文
     *
     * @param number
     * @return
     */
    private String convertToEnglish(int number) {
        String[] numbers = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve"};
        if (number >= 0 && number < numbers.length) {
            return numbers[number];
        } else {
            return "unknown";
        }
    }

    /**
     * 批量合并学生
     *
     * @return
     * @throws Exception
     */
    @GetMapping("/updateStudentBatch")
    public Result updateStudentBatch() throws Exception {
        Long studentId = 1624742592098861056L;
        Long toStudentId = 1624794064735961088L;
        //iStudentService.updateStudentBatch();
        return new Result(Code.GET_OK, "", Code.GET_OK_MSG);
    }

    @ApiOperation("根据学员档案显示学员成绩")
    @GetMapping("/transcriptByStudentId")
    public Result transcriptByStudentId(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                        @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                        @RequestParam(value = "subjectsId", defaultValue = "") String subjectsId,
                                        @RequestParam(value = "studentId", defaultValue = "") String studentId,
                                        @RequestParam(value = "yearPart", defaultValue = "") String yearPart,
                                        @RequestParam(value = "quarterNum", defaultValue = "") String quarterNum,
                                        @RequestParam(value = "examNum", defaultValue = "") String examNum,
                                        @RequestParam(value = "yearClassId", defaultValue = "") String yearClassId) {
        IPage<Transcript> iPage = new Page<>(pageNum, pageSize);
        QueryWrapper<Transcript> transcriptQueryWrapper = new QueryWrapper<>();
        transcriptQueryWrapper.in("school_id", this.baseSchoolIdList);
        transcriptQueryWrapper.eq("student_id", studentId);
        transcriptQueryWrapper.eq(StringUtils.isNotBlank(subjectsId), "subjects_id", subjectsId);
        transcriptQueryWrapper.eq(StringUtils.isNotBlank(yearPart), "year_part", yearPart);
        transcriptQueryWrapper.eq(StringUtils.isNotBlank(quarterNum), "quarter_num", quarterNum);
        transcriptQueryWrapper.eq(StringUtils.isNotBlank(examNum), "exam_num", examNum);
        transcriptQueryWrapper.eq(StringUtils.isNotBlank(yearClassId), "year_class_id", yearClassId);
        transcriptQueryWrapper.notIn("grade_section", 0, 3);

        iTranscriptService.page(iPage, transcriptQueryWrapper);
        for (Transcript transcript : iPage.getRecords()) {
            Student student = iStudentService.getById(transcript.getStudentId());
            if (student != null) {
                transcript.setHeadImg(student.getHeadImg());
            }
            if (transcript.getSubjectsId() != null) {
                String subjectsName = CommonUtil.getSubjectsNameForId(Integer.parseInt(transcript.getSubjectsId().toString()));
                transcript.setSubjectsName(subjectsName);
            }
        }
        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));
    }

    @ApiOperation("根据学员档案显示学员信息")
    @GetMapping("/informationByStudentId")
    public Result informationByStudentId(@RequestParam(value = "subjectsId", defaultValue = "") String subjectsId,
                                         @RequestParam(value = "yearPart", defaultValue = "") String yearPart,
                                         @RequestParam(value = "quarterNum", defaultValue = "") String quarterNum,
                                         @RequestParam(value = "studentId", defaultValue = "") String studentId) {
        QueryWrapper<StudentGrade> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(subjectsId), "subjects_id", subjectsId);
        queryWrapper.eq("student_grade.year_part", yearPart);
        queryWrapper.eq("student_grade.quarter_num", quarterNum);
        queryWrapper.eq("student_grade.student_id", studentId);
        queryWrapper.eq("student_grade.lesson_type", 1);
        queryWrapper.groupBy("grade.id");

        List<Grade> studentGrades = iStudentGradeService.getGrade(queryWrapper);
        CommonUtil commonUtil = new CommonUtil();
        List<HashMap<String, Object>> mapList = new ArrayList<>();

        for (Grade grade : studentGrades) {
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("gradeName", grade.getName());
            hashMap.put("yearClass", grade.getYearClassId());
            hashMap.put("yearClassId", grade.getYearClassInt());
            hashMap.put("gradeId", grade.getId());
            hashMap.put("gradeSection", commonUtil.getGradeSectionForYearClassId(grade.getYearClassInt()));
            mapList.add(hashMap);
        }

        return new Result(Code.OK, mapList, Code.GET_OK_MSG);
    }


    @Transactional
    @ApiOperation("根据学员档案添加修改学员成绩")
    @PostMapping("/transcriptByStudentId")
    public Result save(@RequestBody StudentTranscriptItem studentTranscriptItem) {
        TranscriptSet transcriptSet = iTranscriptSetService.getById("1646797065822404608");
        Quarter quarter = iQuarterService.getQuarterForYearAndNum(transcriptSet.getTeacherYearPart(), transcriptSet.getTeacherQuarterNum());
        StringBuilder stringBuilder = new StringBuilder();
        for (SubjectsScore subjectsScore : studentTranscriptItem.getSubjectsScoreList()) {
            subjectsScore.setReadingSchoolId(studentTranscriptItem.getReadingSchoolId());//报读学校
            if (StringUtils.isNotBlank(subjectsScore.getScore()) && !validateNumber(subjectsScore.getScore())) {
                StudentAtSchool studentAtSchool = iStudentAtSchoolService.getById(subjectsScore.getReadingSchoolId());
                if (studentAtSchool == null) {
                    stringBuilder.append(subjectsScore.getReadingSchoolId()).append("学校不存在").append(",");
                } else {
                    QueryWrapper<StudentAtSchoolScoreDivide> studentAtSchoolScoreDivideQueryWrapper = new QueryWrapper<>();
                    studentAtSchoolScoreDivideQueryWrapper.eq("student_at_school_id", subjectsScore.getReadingSchoolId());
                    studentAtSchoolScoreDivideQueryWrapper.eq("grade_section", studentTranscriptItem.getGradeSection());
                    studentAtSchoolScoreDivideQueryWrapper.eq("score", subjectsScore.getScore().trim());
                    studentAtSchoolScoreDivideQueryWrapper.last("limit 1");
                    StudentAtSchoolScoreDivide studentAtSchoolScoreDivide = iStudentAtSchoolScoreDivideService.getOne(studentAtSchoolScoreDivideQueryWrapper);
                    if (studentAtSchoolScoreDivide == null) {
                        stringBuilder.append(studentTranscriptItem.getName()).append(subjectsScore.getScore()).append(",系统不存在学校：").append(studentAtSchool.getName()).append("分段").append(",");
                    }
                }
            }
        }

        if (stringBuilder.length() > 0) {
            return new Result(Code.ERROR, "", stringBuilder.toString() + "保存失败");
        }

        Student student = iStudentService.getById(studentTranscriptItem.getId());
        for (SubjectsScore subjectsScore : studentTranscriptItem.getSubjectsScoreList()) {
            subjectsScore.setReadingSchoolId(studentTranscriptItem.getReadingSchoolId());//报读学校
            if (StringUtils.isNotBlank(subjectsScore.getScore())) {
                Transcript transcript = iTranscriptService.getOneForQuarter(quarter.getYearPart(), quarter.getNum(), subjectsScore.getSubjectsId(), studentTranscriptItem.getId(), transcriptSet.getTeacherExamNum());
                if (transcript == null) {
                    transcript = new Transcript();
                    transcript.setId(idWorker.nextId());
                }
                transcript.setScore(subjectsScore.getScore());
                transcript.setRemark(subjectsScore.getRemark());

                if (StringUtils.isEmpty(subjectsScore.getScore())) {
                    transcript.setScore("0");
                    transcript.setIsStatistics(0);
                    transcript.setScoreType(0);
                    continue;
                } else {
                    if (subjectsScore.getScore() != null && subjectsScore.getScore().equals("0")) {
                        continue;
                    }
                    if (validateNumber(subjectsScore.getScore())) {
                        BigDecimal score = new BigDecimal(subjectsScore.getScore());
                        transcript.setScoreStart(score);
                        transcript.setScoreEnd(score);
                        transcript.setScoreType(1);//分数类型：1为数字，2为字母
                    } else {
                        iStudentAtSchoolService.getById(subjectsScore.getReadingSchoolId());
                        QueryWrapper<StudentAtSchoolScoreDivide> studentAtSchoolScoreDivideQueryWrapper = new QueryWrapper<>();
                        studentAtSchoolScoreDivideQueryWrapper.eq("student_at_school_id", subjectsScore.getReadingSchoolId());
                        studentAtSchoolScoreDivideQueryWrapper.eq("grade_section", studentTranscriptItem.getGradeSection());
                        studentAtSchoolScoreDivideQueryWrapper.eq("score", subjectsScore.getScore().trim());
                        studentAtSchoolScoreDivideQueryWrapper.last("limit 1");
                        StudentAtSchoolScoreDivide studentAtSchoolScoreDivide = iStudentAtSchoolScoreDivideService.getOne(studentAtSchoolScoreDivideQueryWrapper);
                        transcript.setScoreStart(studentAtSchoolScoreDivide.getScoreStart());
                        transcript.setScoreEnd(studentAtSchoolScoreDivide.getScoreEnd());
                        transcript.setScoreType(2);//分数类型：1为数字，2为字母
                    }
                    transcript.setIsStatistics(1);
                    if (subjectsScore.getReadingSchoolId() != null && StringUtils.isNotBlank(String.valueOf(subjectsScore.getReadingSchoolId()))) {
                        if (student != null) {
                            student.setReadingSchoolId(transcript.getReadingSchoolId());
                            iStudentService.updateById(student);
                        }
                    }
                }
                StudentGrade studentGrade = iStudentGradeService.getStudentForLast(quarter.getYearPart(), quarter.getNum(), subjectsScore.getSubjectsId(), studentTranscriptItem.getId(), 1);
                if (studentGrade != null) {
                    Organization organization = iOrganizationService.getById(studentGrade.getSchoolId());
                    transcript.setSchoolId(studentGrade.getSchoolId());
                    transcript.setSchoolName(organization.getName());
                    transcript.setYearClassId(studentGrade.getYearClassId());
                    transcript.setYearClassName(CommonUtil.getYearClassNameForId(studentGrade.getYearClassId()));
                    Grade grade = iGradeService.getById(studentGrade.getGradeId());
                    if (grade != null) {
                        transcript.setTeacherId(grade.getTeacherId());
                        transcript.setGradeId(grade.getId());
                        transcript.setGradeName(grade.getName());
                        Staff staff = iStaffService.getOneById(grade.getTeacherId());
                        if (staff != null) {
                            transcript.setTeacherName(staff.getName());
                        }
                    }
                } else {
                    transcript.setSchoolId(studentTranscriptItem.getSchoolId());
                    transcript.setYearClassId(studentTranscriptItem.getYearClassId());
                    transcript.setYearClassName(CommonUtil.getYearClassNameForId(studentTranscriptItem.getYearClassId()));
                    transcript.setGradeSection(studentTranscriptItem.getGradeSection());
                }
                transcript.setGradeSection(studentTranscriptItem.getGradeSection());
                transcript.setYearPart(quarter.getYearPart());
                transcript.setQuarterNum(quarter.getNum());
                transcript.setQuarterName(quarter.getAliasName());
                transcript.setStudentId(student.getId());
                transcript.setStudentName(student.getName());
                transcript.setExamNum(transcriptSet.getTeacherExamNum());
                transcript.setExamName(transcriptSet.getTeacherExamName());
                transcript.setReadingSchoolId(subjectsScore.getReadingSchoolId());
                transcript.setSubjectsId(subjectsScore.getSubjectsId());
                transcript.setSubjectsName(CommonUtil.getSubjectsNameForId(Integer.parseInt(subjectsScore.getSubjectsId().toString())));
                iTranscriptService.saveOrUpdate(transcript);
            }
        }

        return new Result(Code.OK, "", Code.SAVE_OK_MSG);
    }

    @ApiOperation("所有学员姓名转音频地址")
    @GetMapping("tts")
    public Result tts() {
        iAliyunApiService.studentAudioBatch();
        return new Result(Code.OK, "", "更新中");
    }

    /**
     * 直系亲属页面，获取在读、预分班学生和学生对应课程
     */
    @ApiOperation("获取学生和课程")
    @GetMapping("getStudentIdAndCourseId")
    public Result getStudentIdAndCourseId(@RequestParam Map reMap) {
        Integer pageNum = StringUtils.isEmpty((String) reMap.get("pageNum")) ? 1 : Integer.valueOf((String) reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty((String) reMap.get("pageSize")) ? 10 : Integer.valueOf((String) reMap.get("pageSize"));
        Page<StudentGrade> iPage = new Page<>(pageNum, pageSize);
        String studentName = (String) reMap.get("studentName");

        IPage<StudentGrade> studentGradeIPage = iStudentService.getStudentIdByReading(iPage, studentName);
        Quarter quarter = iQuarterService.getNowQuarter();
        List<HashMap<String, Object>> list = new ArrayList<>();
        for (StudentGrade studentGrade : studentGradeIPage.getRecords()) {
            HashMap hashMap = new HashMap<>();
            List details = new ArrayList<>();

            hashMap.put("studentId", studentGrade.getStudentId());
            hashMap.put("studentName", studentGrade.getStudentName());
            hashMap.put("headImg", studentGrade.getHeadImg());
            List<StudentGrade> studentGrades = studentMapper.getByStudentIdDetails(studentGrade.getStudentId(), quarter.getYearPart(), quarter.getNum());
            if (studentGrades != null) {
                for (StudentGrade grade : studentGrades) {
                    HashMap map = new HashMap<>();
                    map.put("courseId", grade.getCourseId());
                    map.put("schoolId", grade.getSchoolId());
                    map.put("schoolName", grade.getSchoolName());
                    map.put("courseName", grade.getCourseName());
                    details.add(map);
                }
            }
            hashMap.put("details", details);
            list.add(hashMap);
        }

        return new Result(Code.OK, new PageResult<>(list, studentGradeIPage.getTotal(), studentGradeIPage.getPages()), Code.GET_OK_MSG);
    }

    /**
     * 查询学生的亲属
     */
    @ApiOperation("查询学生的亲属")
    @GetMapping("kinsfolk")
    public Result getKinsfolk(@RequestParam Map reMap) {
        String studentId = (String) reMap.get("studentId");
        List<StudentGrade> studentGradeList = studentMapper.getKinsfolk(Long.parseLong(studentId));
        Quarter quarter = iQuarterService.getNowQuarter();
        List<HashMap<String, Object>> list = new ArrayList<>();
        for (StudentGrade studentGrade : studentGradeList) {
            HashMap hashMap = new HashMap<>();
            List details = new ArrayList<>();
            hashMap.put("studentId", studentGrade.getStudentId());
            hashMap.put("studentName", studentGrade.getStudentName());
            hashMap.put("headImg", studentGrade.getHeadImg());

            List<StudentGrade> studentGrades = studentMapper.getByStudentIdDetails(studentGrade.getStudentId(), quarter.getYearPart(), quarter.getNum());
            if (studentGrades != null) {
                for (StudentGrade grade : studentGrades) {
                    HashMap map = new HashMap<>();
                    map.put("courseId", grade.getCourseId());
                    map.put("schoolId", grade.getSchoolId());
                    map.put("schoolName", grade.getSchoolName());
                    map.put("courseName", grade.getCourseName());
                    details.add(map);
                }
            }
            hashMap.put("details", details);
            list.add(hashMap);
        }

        return new Result(Code.OK, list, Code.GET_OK_MSG);
    }

}
